(defun primep(n)
  (cond 
    ((< n 0) (primep (- n)))
    ((= n 1) nil)
    ((or (<= n 3) (= n 5) (= n 7) (= n 11)) t)
    ((or (= n 4) (= n 6) (= n 8) (= n 9)) nil)
    ((zerop (mod n 2)) nil)
    (t (loop 
	  for i = 3 then (+ 2 i) 
	  with lim = (sqrt n) 
	  while (<= i lim) 
	  when (zerop (mod n i)) do (return nil) 
	  finally (return t)))))

(defun digits (n)
  (if (< n 10) 
      1
      (1+ (digits (floor (/ n 10))))))

(defun first-digit(n)
  (if (< n 10)
      n
      (first-digit (floor (/ n 10)))))

(defun last-digit (n)
  (mod n 10))

(defun drop-first-digit(n)
  (if (< n 10) 0
      (+ (mod n 10) (* 10 (drop-first-digit (floor (/ n 10)))))))

(defun drop-last-digit(n)
  (floor (/ n 10)))

(defun iter-prime(n f)
  (if (< n 10) 
      (primep n)
      (and (primep n) (iter-prime (funcall f n) f))))

(defun probl37(max)
  (loop 
     with primes = nil 
     until (= (length primes) max)
     for i = 11 then (+ 2 i)
     when (and 
	   (primep (last-digit i))
	   (primep (first-digit i))
	   (primep i)
	   (iter-prime i #'drop-last-digit)
	   (iter-prime i #'drop-first-digit))
     do (setf primes (cons i primes))
     finally (return primes)))